from multiprocessing import Process, Queue
from multiprocessing import Lock as Lock_m
from threading import Thread, Lock
# 多进程锁
def save_to_file(index, lock):
    with lock:
        with open("test.log", "a", encoding="utf-8") as f:
            f.write(str(index) + '\n')


# 多线程锁
x = 0
lock_t = Lock()
def foo():
    global x
    for r in range(10**5):
        with lock_t:
            x += 1
            x -= 1


# 消息队列
def save_to_queue(index, my_queue):
    my_queue.put(index)



if __name__ == "__main__":
    process_array = []
    lock = Lock_m()
    for i in range(10):
        p = Process(target=save_to_file, args=(i, lock))
        process_array.append(p)
        p.start()
    for p in process_array:
        p.join()
    print("done!")


    thread_array = []
    for w in range(2):
        t = Thread(target=foo)
        thread_array.append(t)
        t.start()
    for t in thread_array:
        t.join()
    print(x)


    queque_array = []
    my_queque = Queue()
    for e in range(10):
        q = Process(target=save_to_queue, args=(e, my_queque))
        queque_array.append(q)
        q.start()
    for q in queque_array:
        q.join()
        print(my_queque.get())
    print("Done!")
